package cn.itzzx.lagou.mybatis.session;

import cn.itzzx.lagou.mybatis.pojo.Configuration;
import cn.itzzx.lagou.mybatis.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * MyBatis API 完成数据库的曾删改查功能
 * @author Martin
 * @date 2020-04-25
 * @see 1.0
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public <E> List<E> selectList(String statementId, Object... parameter) throws SQLException, ClassNotFoundException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.query(configuration,mappedStatement,parameter);
    }

    @Override
    public <E> E selectOne(String statementId, Object... parameter) throws IllegalAccessException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, ClassNotFoundException {
        List<Object> objects = selectList(statementId, parameter);
        if(objects.size()==1){
            return (E) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public int update(String statementId, Object... parameter) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration,mappedStatement,parameter);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        return configuration.getMapper(mapperClass,this);
    }
}
